package com.xtedu.examproject.scheduler.job;

import com.xtedu.examproject.entity.ExamQuestion;
import com.xtedu.examproject.entity.Examination;
import com.xtedu.examproject.service.ExamQuestionRelaService;
import com.xtedu.examproject.service.ExaminationService;
import com.xtedu.examproject.util.RedisUtil;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;

public class ExamStartStatusJob implements Job {

    private final ExaminationService examinationService = new ExaminationService();
    private final ExamQuestionRelaService examQuestionRelaService = new ExamQuestionRelaService();

    @Override
    public void execute(JobExecutionContext context){
        try {
            System.out.println("开始执行试卷预加载任务");

            // 获取所有即将开始的考试
            List<Examination> examinations = examinationService.getAllExamination();
            LocalDateTime now = LocalDateTime.now();

            for (Examination exam : examinations) {
                // 只处理未开始的考试
                if (exam.getState() != 0) {
                    continue;
                }

                // 判断考试时间
                Timestamp startTime = exam.getStartTime();
                if (startTime == null) {
                    continue;
                }

                LocalDateTime examStartTime = startTime.toLocalDateTime();
                // 计算距离考试开始还有多少分钟
                long minutesToStart = ChronoUnit.MINUTES.between(now, examStartTime);

                // 如果考试将在5分钟内开始，预加载试卷到Redis
                if (minutesToStart > 0 && minutesToStart <= 5) {
                    String redisKey = "examPaper:" + exam.getId();

                    // 检查是否已经加载过试卷
                    if (!RedisUtil.exists(redisKey)) {
                        // 从未开始的考试中获取试卷题目
                        List<ExamQuestion> examQuestions = examQuestionRelaService.findByExamId(exam.getId());

                        if (examQuestions != null && !examQuestions.isEmpty()) {
                            // 将试卷信息存储到Redis中
                            RedisUtil.setObject(redisKey, examQuestions);
                            // 设置过期时间到考试结束后一段时间
                            long expireTime = exam.getDuration() * 60 + 3600; // 考试时长+1小时
                            RedisUtil.expire(redisKey, expireTime);

                            System.out.println("已为考试ID " + exam.getId() + " 预加载试卷到Redis");
                        }
                    }
                }
            }

            System.out.println("试卷预加载任务执行完成");
        } catch (Exception e) {
            System.err.println("执行试卷预加载任务时发生错误: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
